package com.kyubi.common.data;


import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Set;
import java.util.Vector;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import com.kyubi.common.config.ConfigKeys;
import com.kyubi.common.config.Configuration;


public class InstanceToXMLConvertor {

	private Instances insts;
	private String outFilePath;
	private Configuration config = Configuration.getSingleton();
	
	public InstanceToXMLConvertor(Instances insts, String outFilePath) {
		this.insts = insts;
		this.outFilePath = outFilePath;
	}
	
	public void convert() {
		Element root = new Element(config.get(ConfigKeys.ROOT_TAG));
		Document doc = new Document(root);
		
		// add meta-data
		Set<String> keys = insts.getMetaKeys();
		for(String key : keys) {
			String value = insts.getMetaData(key);
			
			Element elem = new Element(key);
			elem.addContent(value);
			root.addContent(elem);
		}
		
		// add data
		//Vector<String> data = insts.getData();
		for(int i=0; i<insts.size(); i++) {
			String value = insts.getDataAt(i);
			//boolean label = insts.getLabelAt(i);
			
			Element elem = new Element(config.get(ConfigKeys.DATA_TAG));
			//elem.setAttribute(new Attribute("class", String.valueOf(label)));
			elem.addContent(value);
			root.addContent(elem);
		}
		
//		try {
//		    XMLOutputter outputter = new XMLOutputter();
//		    outputter.output(doc, System.out);
//		} catch (java.io.IOException e) {
//		    e.printStackTrace();
//		}

		try {
		    XMLOutputter outputter = new XMLOutputter();
		    FileOutputStream fos = new FileOutputStream(outFilePath);
			Writer out = new OutputStreamWriter(fos, "UTF8");
			out.write(outputter.outputString(doc));
			out.close();
		} catch(Exception e) {
			e.printStackTrace();
		}

	}
}
